from sqlalchemy.orm import Session
from schema import User_Farm_schema
from model import User_Farm_model



def get_User_Farm(db: Session, ID: int):
    return db.query(User_Farm_model.User_farm).filter(User_Farm_model.User_farm.ID == ID).first()


def get_all_User_Farm(db: Session):
    return db.query(User_Farm_model.User_farm).all()


def delete_User_Farm(db: Session, ID):
    to_delete = db.query(User_Farm_model.User_farm).filter(User_Farm_model.User_farm.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_User_Farm(db: Session, User_Farm: User_Farm_schema.User_farm):
    db_User_Farm = User_Farm_model.User_farm(
        FarmID=User_Farm.FarmID,
        AdminID=User_Farm.AdminID,
        Remarks=User_Farm.Remarks,
    )
    db.add(db_User_Farm)
    db.commit()
    db.refresh(db_User_Farm)
    return db_User_Farm


def update_User_Farm(db: Session, ID, field_name, new_value):
    db_User_Farm = db.query(User_Farm_model.User_farm).filter(User_Farm_model.User_farm.ID == ID).first()
    setattr(db_User_Farm, field_name, new_value)
    db.commit()
    db.refresh(db_User_Farm)
    return db_User_Farm
